package app;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

import java.net.URLEncoder;

public class ContentWriter {

    public String url;

    public String msgBody;

    private static final String encoding =  "UTF-8";

    public ContentWriter(String url , String msgBody )
    {
        this.url = url;
        this.msgBody = msgBody;
    }


    protected String makeParam( String name , String value ) throws UnsupportedEncodingException
    {
        return URLEncoder.encode( name , encoding  ) + "=" + URLEncoder.encode( value , encoding  );
    }

    protected String makeReqParams() throws UnsupportedEncodingException
    {
        String result = "";

        result = makeParam( "message" , msgBody );


        return result;
    }

    public String getContent() throws Exception
    {

        Reader r = new StringReader( makeReqParams() );

        StringWriter w = new StringWriter();

        postData( r , new URL(url) , w );

        r.close();

        String responseBody = w.getBuffer().toString();

        w.close();

        return responseBody;
    }

    /**
     * Reads data from the data reader and posts it to a server via POST request.
     * data - The data you want to send
     * endpoint - The server's address
     * output - writes the server's response to output
     * @throws Exception
     */
    public static void postData(Reader data, URL endpoint, Writer output) throws Exception {
        HttpURLConnection urlc = null;
        try {
            urlc = (HttpURLConnection) endpoint.openConnection();
            try {
                urlc.setRequestMethod("POST");
            } catch (ProtocolException e) {
                throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
            }
            urlc.setDoOutput(true);
            urlc.setDoInput(true);
            urlc.setUseCaches(false);
            urlc.setAllowUserInteraction(false);
            urlc.setRequestProperty("Content-type", "text/xml; charset=" + encoding);
            
            OutputStream out = urlc.getOutputStream();

            try {
                Writer writer = new OutputStreamWriter(out, encoding);
                pipe(data, writer);
                writer.close();
            } catch (IOException e) {
                throw new Exception("IOException while posting data", e);
            } finally {
                if (out != null) {
                    out.close();
                }
            }

            InputStream in = urlc.getInputStream();
            try {
                Reader reader = new InputStreamReader(in);
                pipe(reader, output);
                reader.close();
            } catch (IOException e) {
                throw new Exception("IOException while reading response", e);
            } finally {
                if (in != null) {
                    in.close();
                }
            }

        } catch (IOException e) {
            throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
        } finally {
            if (urlc != null) {
                urlc.disconnect();
            }
        }
    }

    /**
     * Pipes everything from the reader to the writer via a buffer
     */
    private static void pipe(Reader reader, Writer writer) throws IOException {
        char[] buf = new char[1024];
        int read = 0;
        while ((read = reader.read(buf)) >= 0) {
            writer.write(buf, 0, read);
        }
        writer.flush();
    }
}
